import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { Button, Typography, message, Modal, Drawer, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import Search from "@/components/Student/search";
import StudentDetailModal from '@/components/Student/StudentDetailModal';
import BlackStudent from '@/components/Student/BlackStudent';
import StudentFormModal from '@/components/Student/StudentFormModal';
import JoinGroupModal from '@/components/Student/JoinGroupModal';
import EvaluationModal from '@/components/Student/EvaluationModal';
import StudentTable from '@/components/Student/StudentTable';

import { useStudentData } from '@/hooks/useStudentData';
import { useDepartmentData } from '@/hooks/useDepartmentData';
import { Student, getStudentById, getStudentGroupTeachers, addStudentEvaluation, removeFromBlacklist } from '@/utils/api/student/student';
import { Teacher } from '@/utils/api/teacher/teacher';
import ResetPasswordModal from '@/components/Student/ResetPasswordModal';

const { Title } = Typography;

const StudentList: React.FC = () => {
    const pageSize = 10;
    const {
        students,
        total,
        loading,
        searchParams,
        fetchStudents,
        handleSearch,
        handleReset,
        handleDelete,
        handleJoinGroup,
        handleExitGroup,
        setLoading
    } = useStudentData({ pageSize });

    const {
        departmentOptions,
        allMajorOptions,
        departmentMajorMap,
        fetchAllData
    } = useDepartmentData();

    const [pagination, setPagination] = useState({
        current: 1,
        pageSize,
    });

    const [currentStudent, setCurrentStudent] = useState<Student | null>(null);
    const [currentId, setCurrentId] = useState<number | null>(null);

    const [formModalVisible, setFormModalVisible] = useState<boolean>(false);
    const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
    const [joinModalVisible, setJoinModalVisible] = useState<boolean>(false);
    const [evaluationModalVisible, setEvaluationModalVisible] = useState<boolean>(false);
    const [blackModalVisible, setBlackModalVisible] = useState<boolean>(false);

    const [evaluationTeachers, setEvaluationTeachers] = useState<Teacher[]>([]);
    const [selectedStudentId, setSelectedStudentId] = useState<number | null>(null);
    const [selectedBlackStudent, setSelectedBlackStudent] = useState<Student | null>(null);

    const pageSizeOptions = useMemo(() => ['10', '20', '50', '100'], []);

    const [resetPasswordVisible, setResetPasswordVisible] = useState<boolean>(false);
    const [resetPasswordStudentId, setResetPasswordStudentId] = useState<number | null>(null);
    const [resetPasswordStudentName, setResetPasswordStudentName] = useState<string>('');

    // 抽屉状态
    const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
    const [currentStudentRecord, setCurrentStudentRecord] = useState<Student | null>(null);

    // 初始加载数据
    useEffect(() => {
        fetchStudents(1, pageSize);
    }, [fetchStudents, pageSize, fetchAllData]);

    // 处理表格分页变化
    const handleTableChange = useCallback((page: number, pageSize?: number) => {
        const newPageSize = pageSize || pagination.pageSize;
        setPagination({
            current: page,
            pageSize: newPageSize,
        });
        fetchStudents(page, newPageSize, searchParams);
    }, [fetchStudents, pagination.pageSize, searchParams]);

    // 处理新增学生
    const handleAdd = useCallback(() => {
        setCurrentId(null);
        setCurrentStudent(null);
        setFormModalVisible(true);
    }, []);

    // 处理编辑学生
    const handleEdit = useCallback(async (id: number) => {
        try {
            setLoading(true);
            setCurrentId(id);
            const response = await getStudentById(id);
            const student = response.data;
            setCurrentStudent(student);
            setFormModalVisible(true);
        } catch (error) {
            console.error('获取学生详情失败:', error);
        } finally {
            setLoading(false);
        }
    }, [setLoading]);

    // 处理查看详情
    const handleDetail = useCallback(async (id: number) => {
        try {
            setLoading(true);
            setCurrentId(id);
            const response = await getStudentById(id);
            const student = response.data;
            setCurrentStudent(student);
            setDetailModalVisible(true);
        } catch (error) {
            console.error('获取学生详情失败:', error);
        } finally {
            setLoading(false);
        }
    }, [setLoading]);

    // 处理表单提交成功
    const handleFormSubmitSuccess = useCallback(() => {
        fetchStudents(pagination.current, pagination.pageSize, searchParams);
    }, [fetchStudents, pagination.current, pagination.pageSize, searchParams]);

    // 处理评价
    const handleEvaluate = useCallback(async (student: Student) => {
        if (!student.groupId) {
            message.warning('该学生未加入任何小组，无法评价');
            return;
        }

        try {
            setLoading(true);
            setCurrentStudent(student);

            // 获取该学生所在小组的指导老师
            const response = await getStudentGroupTeachers(student.groupId);
            if (response.code === 200) {
                const teachers = response.data || [];
                setEvaluationTeachers(Array.isArray(teachers) ? teachers : []);
                setEvaluationModalVisible(true);
            }
        } catch (error) {
            console.error('获取指导老师失败:', error);
        } finally {
            setLoading(false);
        }
    }, [setLoading]);

    // 处理提交评价
    const handleEvaluationSubmit = useCallback(async (teacherId: number, evaluation: string) => {
        try {
            setLoading(true);

            const evaluationData = {
                studentId: currentStudent?.id as number,
                studentName: currentStudent?.name,
                teacherId,
                teacherName: evaluationTeachers.find(t => t.id === teacherId)?.name,
                evaluation
            };

            const response = await addStudentEvaluation(evaluationData);
            if (response.code === 200) {
                message.success('评价成功');
                setEvaluationModalVisible(false);
            }
        } catch (error) {
            console.error('评价失败:', error);
        } finally {
            setLoading(false);
        }
    }, [currentStudent, evaluationTeachers, setLoading]);

    // 处理拉黑学生
    const handleBlackStudent = useCallback((student: Student) => {
        setSelectedBlackStudent(student);
        setBlackModalVisible(true);
    }, []);

    // 处理拉黑成功
    const handleBlackSuccess = useCallback(() => {
        fetchStudents(pagination.current, pagination.pageSize, searchParams);
    }, [fetchStudents, pagination.current, pagination.pageSize, searchParams]);

    // 解除拉黑
    const handleRemoveFromBlacklist = useCallback(async (studentId: number) => {
        Modal.confirm({
            title: "确认解除拉黑",
            content: "确定要解除这名学生的拉黑状态吗？",
            okText: "确认",
            cancelText: "取消",
            onOk: async () => {
                try {
                    setLoading(true);
                    const response = await removeFromBlacklist(studentId);
                    if (response.code === 200) {
                        message.success('解除拉黑成功');
                        fetchStudents(pagination.current, pagination.pageSize, searchParams);
                    }
                } catch (error) {
                    console.error("解除拉黑失败:", error);
                } finally {
                    setLoading(false);
                }
            }
        });
    }, [fetchStudents, pagination.current, pagination.pageSize, searchParams, setLoading]);

    // 处理删除确认
    const handleDeleteConfirm = useCallback((id: number) => {
        Modal.confirm({
            title: "确认删除",
            content: "确定要删除这名学生吗？此操作不可恢复",
            okText: "确认",
            cancelText: "取消",
            onOk: async () => {
                try {
                    await handleDelete(id, pagination.current, students.length);
                } catch (error) {
                    console.error("删除失败:", error);
                }
            }
        });
    }, [handleDelete, pagination.current, students.length]);

    // 处理加入小组
    const handleOpenJoinGroup = useCallback((id: number) => {
        setSelectedStudentId(id);
        setJoinModalVisible(true);
    }, []);

    // 处理确认加入小组
    const handleConfirmJoinGroup = useCallback(async (groupId: number) => {
        if (!selectedStudentId) return;

        try {
            await handleJoinGroup(selectedStudentId, groupId, pagination.current);
            setJoinModalVisible(false);
        } catch (error) {
            console.error('加入小组失败:', error);
        }
    }, [selectedStudentId, handleJoinGroup, pagination.current]);

    // 处理退出小组确认
    const handleExitGroupConfirm = useCallback((studentId: number, groupId: number) => {
        Modal.confirm({
            title: "确认退出",
            content: "确定要退出这个小组吗？",
            okText: "确认",
            cancelText: "取消",
            onOk: async () => {
                try {
                    await handleExitGroup(studentId, groupId, pagination.current);
                } catch (error) {
                    console.error("退出小组失败:", error);
                }
            }
        });
    }, [handleExitGroup, pagination.current]);

    // 添加重置密码处理函数
    const handleResetPassword = useCallback((studentId: number, studentName: string) => {
        setResetPasswordStudentId(studentId);
        setResetPasswordStudentName(studentName);
        setResetPasswordVisible(true);
    }, []);

    // 添加重置密码成功处理函数
    const handleResetPasswordSuccess = useCallback(() => {
        fetchStudents(pagination.current, pagination.pageSize, searchParams);
    }, [fetchStudents, pagination.current, pagination.pageSize, searchParams]);

    // 打开抽屉
    const handleOpenDrawer = useCallback((student: Student) => {
        setCurrentStudentRecord(student);
        setDrawerVisible(true);
    }, []);

    // 关闭抽屉
    const handleCloseDrawer = useCallback(() => {
        setDrawerVisible(false);
        setCurrentStudentRecord(null);
    }, []);

    // 处理抽屉操作
    const handleDrawerAction = useCallback((action: string, record: Student) => {
        handleCloseDrawer();

        switch (action) {
            case 'detail':
                handleDetail(record.id as number);
                break;
            case 'edit':
                handleEdit(record.id as number);
                break;
            case 'evaluate':
                handleEvaluate(record);
                break;
            case 'joinGroup':
                handleOpenJoinGroup(record.id as number);
                break;
            case 'exitGroup':
                if (record.groupId) {
                    handleExitGroupConfirm(record.id as number, record.groupId);
                }
                break;
            case 'blackStudent':
                handleBlackStudent(record);
                break;
            case 'removeFromBlacklist':
                handleRemoveFromBlacklist(record.id as number);
                break;
            case 'resetPassword':
                handleResetPassword(record.id as number, record.name || '');
                break;
            case 'delete':
                handleDeleteConfirm(record.id as number);
                break;
            default:
                break;
        }
    }, [handleCloseDrawer, handleDetail, handleEdit, handleEvaluate, handleOpenJoinGroup, handleExitGroupConfirm, handleBlackStudent, handleRemoveFromBlacklist, handleResetPassword, handleDeleteConfirm]);

    // 传递给Search组件的属性
    const searchProps = useMemo(() => ({
        onSearch: handleSearch,
        onReset: handleReset,
        departmentOptions,
        allMajorOptions,
        departmentMajorMap
    }), [handleSearch, handleReset, departmentOptions, allMajorOptions, departmentMajorMap]);

    // 传递给StudentTable的属性
    const tableProps = useMemo(() => ({
        data: students,
        loading,
        pagination: {
            current: pagination.current,
            pageSize: pagination.pageSize,
            total
        },
        onTableChange: handleTableChange,
        onOpenDrawer: handleOpenDrawer,
        pageSizeOptions
    }), [students, loading, pagination, total, handleTableChange, handleOpenDrawer, pageSizeOptions]);

    return (
        <div className="student-list-container" style={{ padding: '5px' }}>
            <Search {...searchProps} />

            <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '20px',
                paddingBottom: '10px',
                borderBottom: '1px solid #f0f0f0'
            }}>
                <Title level={4} style={{ margin: 0 }}>学生列表</Title>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAdd}
                    className="add-student-btn"
                >
                    新增学生
                </Button>
            </div>

            <StudentTable {...tableProps} />

            <StudentFormModal
                visible={formModalVisible}
                onCancel={() => setFormModalVisible(false)}
                onSubmitSuccess={handleFormSubmitSuccess}
                currentStudent={currentStudent}
                currentId={currentId}
                departmentOptions={departmentOptions}
                allMajorOptions={allMajorOptions}
                departmentMajorMap={departmentMajorMap}
                fetchAllData={fetchAllData}
            />

            <JoinGroupModal
                visible={joinModalVisible}
                onCancel={() => setJoinModalVisible(false)}
                onJoin={handleConfirmJoinGroup}
                loading={loading}
            />

            <EvaluationModal
                visible={evaluationModalVisible}
                onCancel={() => setEvaluationModalVisible(false)}
                onSubmit={handleEvaluationSubmit}
                loading={loading}
                teachers={evaluationTeachers}
                student={currentStudent}
            />

            <StudentDetailModal
                visible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
                studentId={currentId}
                currentStudent={currentStudent}
            />

            <BlackStudent
                visible={blackModalVisible}
                onCancel={() => setBlackModalVisible(false)}
                onSuccess={handleBlackSuccess}
                studentId={selectedBlackStudent?.id as number}
                groupId={selectedBlackStudent?.groupId}
                studentName={selectedBlackStudent?.name || ''}
            />

            <ResetPasswordModal
                visible={resetPasswordVisible}
                onCancel={() => setResetPasswordVisible(false)}
                onSuccess={handleResetPasswordSuccess}
                studentId={resetPasswordStudentId as number}
                studentName={resetPasswordStudentName}
            />

            {/* 操作抽屉 */}
            <Drawer
                title={`操作菜单 - ${currentStudentRecord?.name || ''}`}
                placement="right"
                onClose={handleCloseDrawer}
                open={drawerVisible}
                width={400}
            >
                {currentStudentRecord && (
                    <Space direction="vertical" style={{ width: '100%' }} size="middle">
                        <Button
                            block
                            className="detail-btn"
                            onClick={() => handleDrawerAction('detail', currentStudentRecord)}
                        >
                            详情
                        </Button>
                        <Button
                            block
                            className="edit-btn"
                            onClick={() => handleDrawerAction('edit', currentStudentRecord)}
                        >
                            编辑
                        </Button>
                        <Button
                            block
                            className="evaluate-btn"
                            onClick={() => handleDrawerAction('evaluate', currentStudentRecord)}
                        >
                            评价
                        </Button>
                        {currentStudentRecord.groupId ? (
                            <Button
                                block
                                className="exit-group-btn"
                                onClick={() => handleDrawerAction('exitGroup', currentStudentRecord)}
                            >
                                退出小组
                            </Button>
                        ) : (
                            <Button
                                block
                                className="join-group-btn"
                                disabled={currentStudentRecord.blackType === 1}
                                onClick={() => handleDrawerAction('joinGroup', currentStudentRecord)}
                            >
                                加入小组
                            </Button>
                        )}
                        {currentStudentRecord.blackType === 1 ? (
                            <Button
                                block
                                className="remove-black-btn"
                                onClick={() => handleDrawerAction('removeFromBlacklist', currentStudentRecord)}
                            >
                                解除拉黑
                            </Button>
                        ) : (
                            <Button
                                block
                                className="black-btn"
                                onClick={() => handleDrawerAction('blackStudent', currentStudentRecord)}
                            >
                                拉黑
                            </Button>
                        )}
                        <Button
                            block
                            className="reset-password-btn"
                            onClick={() => handleDrawerAction('resetPassword', currentStudentRecord)}
                        >
                            重置密码
                        </Button>
                        <Button
                            block
                            className="delete-btn"
                            onClick={() => handleDrawerAction('delete', currentStudentRecord)}
                        >
                            删除
                        </Button>
                    </Space>
                )}
            </Drawer>

            <style>{`
                .table-cell {
                    padding: 4px 4px;
                    white-space: nowrap;
                    text-align: center;
                }
                .ant-table-thead > tr > th {
                    position: sticky;
                    top: 0;
                    z-index: 1;
                    background-color: #fafafa;
                    font-weight: 600;
                    text-align: center;
                    padding: 8px 4px;
                }
                
                .ant-table-container {
                    position: relative;
                }
                
                .ant-table-tbody > tr:hover > td {
                    background-color: #f5f5f5;
                }
                
                .add-student-btn {
                    background: linear-gradient(135deg, #1677ff 0%, #40a9ff 100%) !important;
                    border: none !important;
                }
                
                /* 抽屉按钮样式 */
                .ant-drawer-body .ant-btn {
                    background: transparent !important;
                    border: none !important;
                    box-shadow: none !important;
                    text-align: left;
                    padding: 12px 16px;
                    height: auto;
                    border-radius: 6px;
                    transition: all 0.2s ease;
                    color: rgba(0, 0, 0, 0.85);
                    font-size: 14px;
                    display: flex;
                    align-items: center;
                    margin-bottom: 4px;
                    width: 100%;
                    position: relative;
                    overflow: hidden;
                }
                
                /* 按钮悬停效果 */
                .ant-drawer-body .ant-btn:hover {
                    background: rgba(24, 144, 255, 0.1) !important;
                    color: #1890ff !important;
                    transform: translateX(4px);
                }
                
                /* 按钮激活效果 */
                .ant-drawer-body .ant-btn:active {
                    background: rgba(24, 144, 255, 0.2) !important;
                    transform: translateX(4px) scale(0.98);
                }
                
                /* 禁用状态按钮 */
                .ant-drawer-body .ant-btn[disabled] {
                    color: rgba(0, 0, 0, 0.25) !important;
                    background: transparent !important;
                    cursor: not-allowed;
                }
                
                .ant-drawer-body .ant-btn[disabled]:hover {
                    transform: none;
                    color: rgba(0, 0, 0, 0.25) !important;
                    background: transparent !important;
                }
                
                /* 添加按钮图标样式 */
                .ant-drawer-body .ant-btn > .anticon {
                    margin-right: 8px;
                    font-size: 16px;
                    transition: transform 0.2s ease;
                }
                
                .ant-drawer-body .ant-btn:hover > .anticon {
                    transform: scale(1.1);
                }
                
                /* 编辑按钮特殊样式 */
                .ant-drawer-body .edit-btn:hover {
                    background: rgba(82, 196, 26, 0.1) !important;
                    color: #52c41a !important;
                }
                
                .ant-drawer-body .edit-btn:active {
                    background: rgba(82, 196, 26, 0.2) !important;
                }
                
                /* 删除按钮特殊样式 */
                .ant-drawer-body .delete-btn:hover {
                    background: rgba(255, 77, 79, 0.1) !important;
                    color: #ff4d4f !important;
                }
                
                .ant-drawer-body .delete-btn:active {
                    background: rgba(255, 77, 79, 0.2) !important;
                }
                
                /* 评价按钮特殊样式 */
                .ant-drawer-body .evaluate-btn:hover {
                    background: rgba(114, 46, 209, 0.1) !important;
                    color: #722ed1 !important;
                }
                
                .ant-drawer-body .evaluate-btn:active {
                    background: rgba(114, 46, 209, 0.2) !important;
                }
                
                /* 重置密码按钮特殊样式 */
                .ant-drawer-body .reset-password-btn:hover {
                    background: rgba(82, 196, 26, 0.1) !important;
                    color: #52c41a !important;
                }
                
                .ant-drawer-body .reset-password-btn:active {
                    background: rgba(82, 196, 26, 0.2) !important;
                }
                
                /* 拉黑按钮特殊样式 */
                .ant-drawer-body .black-btn:hover {
                    background: rgba(255, 169, 80, 0.1) !important;
                    color: #ffa950 !important;
                }
                
                .ant-drawer-body .black-btn:active {
                    background: rgba(255, 169, 80, 0.2) !important;
                }
                
                /* 解除拉黑按钮特殊样式 */
                .ant-drawer-body .remove-black-btn:hover {
                    background: rgba(0, 168, 84, 0.1) !important;
                    color: #00a854 !important;
                }
                
                .ant-drawer-body .remove-black-btn:active {
                    background: rgba(0, 168, 84, 0.2) !important;
                }
                
                /* 加入小组按钮特殊样式 */
                .ant-drawer-body .join-group-btn:hover {
                    background: rgba(255, 199, 0, 0.1) !important;
                    color: #ffc700 !important;
                }
                
                .ant-drawer-body .join-group-btn:active {
                    background: rgba(255, 199, 0, 0.2) !important;
                }
                
                /* 退出小组按钮特殊样式 */
                .ant-drawer-body .exit-group-btn:hover {
                    background: rgba(24, 144, 255, 0.1) !important;
                    color: #1890ff !important;
                }
                
                .ant-drawer-body .exit-group-btn:active {
                    background: rgba(24, 144, 255, 0.2) !important;
                }
                
                /* 操作按钮样式 */
                .operation-menu-btn {
                    padding: 2px 7px !important;
                    height: 30px !important;
                    
                    background: linear-gradient(135deg, #00b9f6 0%, #4cd1af 100%) !important;
                    border: none !important;
                    color: #ffffff !important;
                    border-radius: 8px;
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    box-shadow: 
                        0 2px 4px rgba(0, 0, 0, 0.2),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1);
    
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    font-weight: 500;
                    font-size: 13px;
                    letter-spacing: 0.3px;
                }

                .operation-menu-btn:hover {
                    background: linear-gradient(135deg, #34495e 0%, #56789a 100%) !important;
                    color: #ffffff !important;
                    transform: translateY(-2px);
                    box-shadow: 
                        0 4px 10px rgba(0, 0, 0, 0.25),
                        inset 0 1px 0 rgba(255, 255, 255, 0.15);
                }

                .operation-menu-btn:active {
                    background: linear-gradient(135deg, #243342 0%, #3a5674 100%) !important;
                    transform: translateY(0);
                    box-shadow: 
                        0 2px 4px rgba(0, 0, 0, 0.2),
                        inset 0 1px 0 rgba(255, 255, 255, 0.05);
                }

                .operation-menu-btn .anticon {
                    font-size: 14px;
                    transition: transform 0.2s ease;
                }

                .operation-menu-btn:hover .anticon {
                    transform: rotate(30deg);
                }

                
                /* 表格中的操作按钮样式 */
                .student-list-container .operation-menu-btn {
                    font-size: 14px;
                    padding: 2px 6px;
                    height: auto;
                }
                
                .ant-btn-primary {
                    transition: all 0.3s ease;
                }
                
                .ant-btn-primary:hover {
                    transform: translateY(-2px);
                }
                
                .ant-btn-primary:active {
                    transform: translateY(0);
                }
            `}</style>
        </div>
    );
};

export default React.memo(StudentList);